<script setup lang="ts">
import { getCurrentInstance, ref, onMounted } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import draggable from 'vuedraggable'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const dragOptions = {
  handle: '.mover',
  animation: 300,
  itemKey: 'id'
}
const items = ref([])

/* ---- */
const layer = ref()
const layerBox = ref()
const layerLoading = ref()

/* ---- */
// --getData--
const getListData = async (callback) => {
  await proxy.$http.get('pro-category/index', {
    params: {
      'ProCategorySearch[dealer_id]': logUser.id,
      'ProCategorySearch[parent_id]': 0,
      // --是否云仓分类--
      'ProCategorySearch[is_store]': 0,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }).then((res) => {
    setListData(res.items).then((result) => { items.value = result })
  }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  callback && callback()
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    let forAdvs = []
    let forAdv = ''
    await proxy.$Myfun.getJsonData(item.icon_json, (resJson) => {
      forAdvs = resJson
      forAdv = resJson[0].image
    })
    // ----
    newItems.push({
      id: item.id,
      name: proxy.$Myfun.setText(item.name),
      image: forAdv,
      advs: forAdvs
    })
  }
  return newItems
}
// ----
const setSortNum = async () => {
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  // ----
  const arr = items.value
  for (let i = 0; i < Number(arr.length); i++) {
    const curItem = arr[i]
    await proxy.$http.patch('pro-category/update?id=' + curItem.id, {
      sort_num: Number(i + 1),
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
  // ----
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
}
// ----
const setDefault = async (item) => {
  let forItems = []
  await proxy.$http.get('pro-category/index', {
    params: {
      'ProCategorySearch[dealer_id]': logUser.id,
      'ProCategorySearch[parent_id]': item.id,
      // --是否云仓分类--
      'ProCategorySearch[is_store]': 0,
      // ----
      page: 1,
      PageSize: 1000000
    }
  }).then((res) => { forItems = res.items }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  if (Number(forItems.length) === 0) return false
  // ----
  for (let i = 0; i < Number(forItems.length); i++) {
    await setSecond(forItems[i])
  }
}
const setSecond = async (item) => {
  await proxy.$http.delete('pro-category/delete?id=' + item.id, {
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
}
const checkInfoDel = async (item) => {
  let newItems = []
  await proxy.$http.get('proc/index', {
    params: {
      'ProductSearch[dealer_id]': logUser.id,
      'ProductSearch[parent_id]': item.id,
      // --是否云仓商品--
      'ProductSearch[is_store]': 0
    }
  }).then((res) => { newItems = res.items }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  if (Number(newItems.length) > 0) {
    proxy.$Myfun.forToast(layer.value, 'open', proxy.$Global.toast.noteCate)
    return false
  }
  // ----
  const options = {
    content: proxy.$Global.layer.conDel,
    button: [{
      text: proxy.$Global.layer.btnCancel
    }, {
      text: proxy.$Global.layer.btnDel,
      class: 'xw-color-24',
      callback: async () => {
        layerBox.value.close()
        // ----
        proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
        // ----
        await setDefault(item)
        // ----
        if (Number(item.advs.length) > 0) {
          const opts = {
            region: proxy.$Global.aoss.region,
            bucket: proxy.$Global.aoss.bucket,
            accessKeyId: proxy.$Global.aoss.accessKeyId,
            accessKeySecret: proxy.$Global.aoss.accessKeySecret
          }
          const imgArr = item.advs
          for (let i = 0; i < Number(imgArr.length); i++) {
            await proxy.$OssUp.ossDelete(opts, imgArr[i].name)
          }
        }
        // ----
        await proxy.$http.delete('pro-category/delete?id=' + item.id, {
          config_id: userInfo.config_id,
          openid: userInfo.openid
        }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
        // ----
        proxy.$Myfun.disLoading(layerLoading.value, 'close')
        getListData()
      }
    }]
  }
  proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
}
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      const forItem = item || {}
      proxy.$Myfun.openPage(proxy, 'push', 'GoodsCateAdm', { id: forItem.id })
      break
    }
    case 2: {
      proxy.$Myfun.openPage(proxy, 'push', 'GoodsCateSon', { id: item.id })
      break
    }
    case 3: {
      checkInfoDel(item)
      break
    }
  }
}

/* ---- */
onMounted(() => {
  getListData(() => {
    proxy.$Myfun.setDragMargin()
  })
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <header class="xw-bg-gray">
      <div class="forTop xw-flex xw-flex-align">
        <div class="TOP-title xw-flex-W1">分类列表</div>
        <span class="TOP-submit xw-WBlue xw-radius-3" @click="getAuditFun(1)">新增一级分类</span>
      </div>
    </header>
    <div class="xw-drag">
      <div class="mescroll-empty" v-if="Number(items.length) === 0"><p class="empty-tip">{{$Global.noData}}</p></div>
      <draggable tag="ul" v-model="items" v-bind="dragOptions" @end="setSortNum" class="list-class xw-flex xw-flex-column" v-else>
        <template #item="{element, index}">
          <li class="xw-Tfg xw-bg-white">
            <div class="LCS-top xw-flex xw-flex-align xw-flex-justify">
              <div class="LCS-img" v-if="element.image"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + element.image + ')' }"></div></div>
              <div class="LCS-title xw-ellipsis xw-flex-W1">{{element.name}}</div>
              <span class="mover LCS-drag xw-act fa fa-bars xw-flex xw-flex-center"></span>
            </div>
            <div class="LCS-con xw-flex xw-flex-align xw-flex-justify">
              <div class="LCS-btn xw-act xw-flex xw-flex-align" @click="getAuditFun(1, element)"><em class="fa fa-edit"></em>修改</div>
              <div class="LCS-btn xw-act xw-flex xw-flex-align" @click="getAuditFun(2, element)"><em class="fa fa-plus"></em>二级分类</div>
              <div class="LCS-btn xw-act xw-flex xw-flex-align" @click="getAuditFun(3, element)"><em class="fa fa-trash-alt"></em>删除</div>
            </div>
          </li>
        </template>
      </draggable>
    </div>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>

<style scoped>
/* ---- */
.list-class li { padding: 1.2rem 1rem; }
.list-class li:before { left: 1rem; }
.list-class li:nth-of-type(1):before { display: none; }
.LCS-img { margin-right: 1rem; width: 5rem; height: 5rem; }
.LCS-title { font-size: 1.6rem; font-weight: bold; }
.LCS-con { margin: 1rem 0 0; }
.LCS-btn em { margin-right: 0.5rem; color: #aaaaaa; }
.LCS-drag { margin-right: -1.2rem; padding: 0 1.2rem; font-size: 2rem; }

/* ---- */
.sortable-chosen { background: #3388ff; color: #ffffff; }
.sortable-chosen .LCS-btn em { color: #ffffff; }
</style>